package user

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"src/config"
	"src/mapper"
	"src/model/ProtoModel"
	service2 "src/service"
	"src/utils"
	"time"
)

type MessageC struct {
}

var MessageCI *MessageC

func NewMessageC() *MessageC {
	return &MessageC{}
}

// post 请求参数 test
func (*MessageC) GetList(b *service2.Req) {
	db := utils.NewDbClient("db", nil)
	var msgs = make([]mapper.Message, 0)
	var err error

	params := b.GetParams()

	if params["page"] == nil {
		params["page"] = "1"
	}

	if params["uid"] == nil {
		b.Fail("uid不能为空")
		return
	}
	page := params["page"].(float64)
	start := int(page)
	if start <= 0 {
		start = 1
	}
	uid := params["uid"].(string)
	where1 := new(mapper.Message)
	where1.Receiver = b.User.Uid
	where1.Sender = uid
	where2 := new(mapper.Message)
	where2.Receiver = uid
	where2.Sender = b.User.Uid
	pageNum := 20
	end := pageNum * start
	err = db.Client.Limit(end-pageNum, end).Or("receiver=? and sender=?", b.User.Uid, uid).Or("receiver=?  and  sender=?", uid, b.User.Uid).Find(&msgs)
	if err != nil {
		b.Fail(err.Error())
		return
	}
	b.Ok(msgs)

}

// post 请求参数 test
func (*MessageC) Send(b *service2.Req) {
	body, err := ioutil.ReadAll(b.R.Body)
	if err != nil {
		log.Println(err)
		b.Fail(err.Error())
		return
	}

	var data ProtoModel.MessageProto
	err = json.Unmarshal(body, &data)
	if err != nil {
		b.Fail(err.Error())
		return
	}
	//
	//data.Id = global.Ws_.Id
	//global.Ws_.Inc()
	//time.Now().Format("2006-01-02 15:04:05")
	data.SendTime = time.Now().Unix()
	db := utils.NewDbClient("db", nil)
	var msg mapper.Message

	err = new(utils.StructUtils).CopyFields(&msg, data)
	msg.SendTime = mapper.JsonTime(time.Unix(data.SendTime, 0))
	extra, err := json.Marshal(data.Extra)
	if err == nil {
		msg.Extra = string(extra)
	}
	content, err := json.Marshal(data.Content)
	if err == nil {
		msg.Content = string(content)
	}

	res, err := db.Client.Insert(&msg)
	if err != nil {
		b.Fail(err.Error())
		return
	}
	log.Println(res)
	//Json结构返回
	if data.Receiver != "" {
		//fmt.Println("data.Msg.Id______", data.Id)
		//msg.Id = id

		err = new(utils.StructUtils).CopyFields(&data, msg)
		var sendData, _ = json.Marshal(&data)
		var api = "http://127.0.0.1:" + config.V().GetString("server.http.port")
		api += "/api/send/toUid"
		log.Println("消息推送到API接口:" + api)
		post, err2 := utils.GetHttpReq().Post(api, sendData)
		if err2 != nil {
			b.Fail(err2.Error())
			return
		}
		var res utils.Result
		err = json.Unmarshal(post, &res)
		if err != nil {
			b.Fail(err.Error())
			return
		}
		if res.Code != 200 {
			res.Data = msg
			b.SetDate(msg)
			b.Fail(res.Msg)
			return
		}
		b.Ok(msg)
		return
		//(&service2.Message{}).SendMsgToUser(&data, data.Receiver)
		// 并发太高会有失败
	}
	b.Fail("接收人不能空")

}
